package image.threshold;

import image.processing.ImageProcessor;
import image.utils.ImageUtilitiesImpl;

import java.awt.image.BufferedImage;
import java.awt.image.WritableRaster;

public class GlobalThresholder {
	public static int MaxChannelValue = 0;
	public static int DELTA_T = 5;

	public int findThresholdValue(BufferedImage src) {

		int T, TOld;
		BufferedImage imagenAux;
		
		if(src.getType() != BufferedImage.TYPE_BYTE_GRAY){
			imagenAux = ImageUtilitiesImpl.getInstance().toGrayScale(src);
		}else{
			imagenAux = src;
		}

		TOld = 0;
		T = 255;
		int iterations = 0;
		do {
			TOld = T;
			T = getNewThresholdValue(imagenAux, T);
			iterations ++;
		} while (Math.abs(T - TOld) > DELTA_T);
		System.out.println("iterations: " + iterations);
		return (int) Math.floor(T);
	}

	private int getNewThresholdValue(BufferedImage img, int T) {
		long minorValues = 0;
		long mayorValues = 0;
		long minorValuesQty = 0;
		long mayorValuesQty = 0;
		WritableRaster raster = img.getRaster();
		for (int x = 0; x < img.getWidth(); x++) {
			for (int y = 0; y < img.getHeight(); y++) {
				int sample = raster.getSample(x, y, 0);
				if (sample > T) {
					mayorValues += sample;
					mayorValuesQty++;
				} else {
					minorValues += sample;
					minorValuesQty++;
				}
			}
		}
		//System.out.println("mayores que "+ T + " :"+ mayorValuesQty +" menores que "+ T + " :"+ minorValuesQty);
		double m1 = mayorValuesQty == 0 ? 0 : (1.0 / mayorValuesQty) * mayorValues;
		//System.out.println("minorValues =" + minorValues);
		double m2 = minorValuesQty == 0 ? 0 : (1.0 / minorValuesQty) * minorValues;
		//System.out.println("m1:" + m1 + "\tm2: " + m2 + "\tret: " + ret);
		return (int) Math.floor((1.0 / 2.0) * (m1 + m2));
	}
}
